<?php

namespace app\api\controller;

use app\admin\model\appmanage\Project;
use app\admin\model\order\AppManage;
use app\common\controller\Api;
use app\common\library\TLSSigAPIv2;
use think\Db;
use think\Validate;

/**
 * IM接口
 */
class Im extends Api
{

    protected $noNeedLogin = ['make_relation','createGroup'];
    protected $noNeedRight = '*';
    protected $appId;

    public function _initialize()
    {
        parent::_initialize();
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app = (new AppManage())->getAppId($url['value']);
        $this->appId = $app['id'];
    }

    /**
     * Notes:获取生成的 UserSig
     * User:yh
     * date:2022/11/18 17:50
     * @throws \Exception
     */
    public function getUserSig()
    {
        /* $param = $this->request->post();
         if(!isset($param['app_tag'])||empty($param['app_tag'])){
             $this->error('请输入APP标识');
         }
         if(!isset($param['user_id'])||empty($param['user_id'])){
             $this->error('请输入用户ID');
         }*/

        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);

        $appid = config('site.IM_AppID', '1400765204');
        $key = config('site.IM_key', '578f96825f4d6999f9a7ded16e727eebf75793e734135fd9874180d0eb31ad68');
//        $identifier = config('site.IM_identifier','administrator');
        $identifier = $app_id['id'] . '_' . $this->auth->id;
        $returnData['UserSig'] = (new TLSSigAPIv2($appid, $key))->genUserSig($identifier);
        $returnData['UserStr'] = $identifier;
        $this->success('获取成功', $returnData);
    }

    //添加好友搜索
    public function search_friend()
    {
        $mobile = $this->request->post('mobile');
        if (!$mobile) {
            $this->error("请输入好友手机号");
        }
        $res = \addons\shopro\model\User::where('mobile', $mobile)->field('id,nickname,avatar')->find();
        if ($res) {
            $r_map = [
                'user_id' => $this->auth->id,
                'f_uid' => $res['id'],
                'relation' => 1
            ];
            $is_friend = Db::table('user_friends')->where($r_map)->count();
            $res['is_friend'] = $is_friend ? true : false;
            $res["ImUserID"] = $this->appId . "_" . $res['id'];
        }
        $this->success('搜索成功', $res);
    }

    //添加好友
    public function add_friend()
    {
        $f_uid = $this->request->post('f_uid');
        $apply_remark = $this->request->post('apply_remark');
        $remark = $this->request->post('remark');
        $f_map = [
            'id' => $f_uid,
            'canceled' => 0
        ];
        $friend = \addons\shopro\model\User::where($f_map)->field('id,nickname,mobile,avatar')->find();
        if ($f_uid == $this->auth->id) {
            $this->error("不能添加自己为好友");
        }
        if (!$friend) {
            $this->error("该用户不存在或已注销");
        }
        $r_map = [
            'user_id' => $this->auth->id,
            'f_uid' => $f_uid,
        ];
        $is_friend = Db::table('user_friends')->where($r_map)->find();
        if (!$is_friend) {
            $data = [
                'user_id' => $this->auth->id,
                'f_uid' => $f_uid,
                'f_nickname' => $friend['nickname'],
                'f_mobile' => $friend['mobile'],
                'f_avatar' => $friend['avatar'],
                'relation' => 3,//1=正常,2=黑名单,3=申请添加
                'apply_remark' => $apply_remark,
                'createtime' => time(),
            ];
            Db::table('user_friends')->insert($data);
        } elseif ($is_friend['relation'] == 1) {
            $this->error("该用户已是您的好友");
        } else {
            $data = [
                'relation' => 3,//1=正常,2=黑名单,3=申请添加
                'apply_remark' => $apply_remark,
                'updatetime' => time(),
            ];
            Db::table('user_friends')->where($r_map)->update($data);
        }
        $this->success('申请发送成功');
    }

    //好友申请列表
    public function apply_list()
    {
        $map = [
            'uf.f_uid' => $this->auth->id,
            'uf.relation' => 3
        ];
        $list = Db::table('user_friends')->alias('uf')->join('user', 'user.id=uf.user_id', "left")->field('user.id,user.nickname,user.avatar,uf.apply_remark')->where($map)->select();
        foreach ($list as $key => $value) {
            if ($value['id']) {
                $list[$key]['ImUserID'] = $this->appId . "_" . $value['id'];
            } else {
                unset($list[$key]);
                continue;
            }
        }
        $this->success('获取成功', array_values($list));
    }

    //拒绝、通过好友申请
    public function apply_handle()
    {
        $friend_id = $this->request->post('friend_id');
        $action = $this->request->post('action');
        if ((!$friend_id) || (!$action)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $map = [
                'user_id' => $friend_id,
                'f_uid' => $this->auth->id,
                'relation' => 3
            ];
            $relation = ($action == "pass") ? 1 : 4; //1=通过，4=拒绝

            //更新好友的通讯录列表
            $res = Db::table('user_friends')->where($map)->update(['relation' => $relation, 'updatetime' => time()]);
            if (!$res) {
                throw new \Exception("该申请已处理，请勿重复操作");
            }
            //通过后 更新自己的通讯录列表
            if ($action == "pass") {
                $f_map = [
                    'id' => $friend_id,
                    'canceled' => 0
                ];
                $friend = \addons\shopro\model\User::where($f_map)->field('id,nickname,mobile,avatar')->find();
                if (!$friend) {
                    throw new \Exception("该用户不存在或已注销");
                }
                $r_map = [
                    'user_id' => $this->auth->id,
                    'f_uid' => $friend_id,
                ];
                $is_friend = Db::table('user_friends')->where($r_map)->count();
                if (!$is_friend) {
                    $data = [
                        'user_id' => $this->auth->id,
                        'f_uid' => $friend_id,
                        'f_nickname' => $friend['nickname'],
                        'f_mobile' => $friend['mobile'],
                        'f_avatar' => $friend['avatar'],
                        'relation' => 1,//1=正常,2=黑名单,3=申请添加
                        'createtime' => time(),
                    ];
                    Db::table('user_friends')->insert($data);
                } else {
                    Db::table('user_friends')->where($r_map)->update(['relation' => 1, "updatetime" => time()]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
        }
        $this->success('操作成功');
    }

    //好友列表
    public function friend_list()
    {
        $offset = $this->request->post('offset', 0);
        $limit = $this->request->post('limit', 20);
        $map = [
            'user_id' => $this->auth->id,
            'relation' => 1 //1=正常,2=黑名单,3=申请添加
        ];
        $total = Db::table('user_friends')
            ->where($map)
            ->count();
        $list = Db::table('user_friends')
            ->where($map)
            ->field('user_id,f_uid,f_role,f_nickname,f_avatar,f_mobile,remark')
            ->limit($offset, $limit)
            ->select();
        $dj = ['无', '推广员', '代言人', '一星网店', '二星网店', '银牌', '金牌', '钻石'];
        foreach ($list as $key => $value) {
            $list[$key]["ImUserID"] = $this->appId . "_" . $value['user_id'];
            $list[$key]["ImFriendID"] = $this->appId . "_" . $value['f_uid'];
            $list[$key]["f_role_txt"] = $dj[$value['f_role']];
        }
        $this->success('获取成功', ['total' => $total, "list" => $list]);
    }

    //好友详情
    public function friend_info()
    {
        $friend_id = $this->request->post('friend_id');
        $f_map = [
            'id' => $friend_id
        ];
        $friend = \addons\shopro\model\User::where($f_map)->field('id,nickname,mobile,avatar,gender')->find();
        if (!$friend) {
            $this->error("该用户不存在或已注销");
        }
        $r_map = [
            'user_id' => $this->auth->id,
            'f_uid' => $friend_id,
            'relation' => 1
        ];
        $is_friend = Db::table('user_friends')->where($r_map)->count();
        $friend['remark'] = Db::table('user_friends')->where($r_map)->value('remark');
        $friend['address'] = null;
        $address = \app\common\model\User::where(['id' => $friend['id']])->value('im_area');
        $friend['address'] = $address;
        $friend['ImUserID'] = $this->appId . "_" . $friend['id'];
        $friend['is_friend'] = $is_friend ? true : false;
        $this->success('获取成功', $friend);
    }

    //修改好友备注
    public function friend_remark()
    {
        $remark = $this->request->post('remark');
        $friend_id = $this->request->post('friend_id');
        if (!$friend_id) {
            $this->error('参数错误');
        }
        $r_map = [
            'user_id' => $this->auth->id,
            'f_uid' => $friend_id,
        ];
        Db::table('user_friends')->where($r_map)->update(['remark' => $remark]);
        $this->success('修改成功');
    }

    //删除好友
    public function del_friend()
    {
        $friend_id = $this->request->post('friend_id');
        $map = [
            'user_id' => $this->auth->id,
            'f_uid' => $friend_id
        ];
        $or_map = [
            'user_id' => $friend_id,
            'f_uid' => $this->auth->id
        ];
        Db::table('user_friends')
            ->where(function ($query) use ($map) {
                $query->where($map);
            })->whereOr(function ($query) use ($or_map) {
                $query->where($or_map);
            })->delete();
        $this->success('删除成功');
    }

    /**
     * 解散群组
     */
    public function destroy_group()
    {
        $GroupId = $this->request->post('group_id');
        if (!$GroupId) {
            $this->error("参数错误");
        }
        $map = [
            'user_id' => $this->auth->id,
            'chat_obj' => $GroupId
        ];
        $group = Db::name('chat_create_log')->where($map)->count();
        if (!$group) {
            $this->error("未找到对应群的创建记录");
        }
        Db::startTrans();
        try {
            $imres = (new \app\common\library\IM)->destroy_group($GroupId);
            Db::name('chat_create_log')->where($map)->delete();
            if (!$imres) {
                throw new \Exception('IM群组解散失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("解散成功");
    }

    /**
     * 上下级添加好友关系
     */
    public function make_relation()
    {
        $pid = $this->request->post('user_id');
        $child_id = $this->request->post('friend_id');
        var_dump((new \app\common\library\IM)->make_relation($pid, $child_id));
    }

    //注销用户时删除好友关系以及腾讯IM账号
    public function del_relation()
    {
        $user_id = $this->request->post('user_id');
        var_dump((new \app\common\library\IM)->del_relation($user_id));
    }

    //使用友聊用户列表
    public function book_user_list()
    {
        $mobile = $this->request->post('mobile/a');
        if (!$mobile) {
            $this->error('参数错误');
        }
        $list = \addons\shopro\model\User::where('mobile', 'in', $mobile)->field('id,nickname,avatar')->select();
        foreach ($list as $key => $value) {
            $r_map = [
                'user_id' => $this->auth->id,
                'f_uid' => $value['id'],
                'relation' => 1
            ];
            $is_friend = Db::table('user_friends')->where($r_map)->count();
            $list[$key]['is_friend'] = $is_friend ? true : false;
            $list[$key]["ImUserID"] = $this->appId . "_" . $value['id'];
        }
        $this->success("获取成功", $list);
    }


    /**
     * 旦米语音模板通知
     */
    public function voice_template()
    {
        $user_id = $this->request->post('user_id');
        $called = \addons\shopro\model\User::where('id', $user_id)->value('mobile');
        if (!Validate::regex($called, "^1\d{10}$")) {
            $this->error("未查询到对应的手机号");
        }
        $dm_url = "https://openapi.danmi.com/voice/voiceTemplate";
        $accountSid = "270ff8dd19a94e3890a874adf62abd70";
        $timestamp = $this->getMillisecond();
        $authtoken = "96bdcbf244c540d08cc3887906be796f";
        $option = [
            "accountSid" => $accountSid,
            "called" => $called,
            "templateId" => 454250,
            "param" => "1",
            "timestamp" => $timestamp,
            "sig" => md5($accountSid . $authtoken . $timestamp)
        ];
        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $dm_url, [
            'form_params' => $option
        ]);
        $req = $res->getBody()->getContents();
        $api_data = json_decode($req, true);
        if ($api_data["respCode"] == "00000") {
            $this->success("请求成功", $api_data['data']);
        } else {
            $this->error("请求失败：" . $api_data['respDesc']);
        }
    }

    //函数,获取毫秒时间戳
    public function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    public function profile()
    {
        $uid = $this->auth->id;
        $map = ['id' => $uid];
        $user = \addons\shopro\model\User::where($map)->field('id,avatar,nickname,gender,birthday,mobile,im_area')->find();
        $user['address'] = $user['im_area'];
        //二维码名片
        $errorCorrectionLevel = 'H'; //容错级别
        $matrixPointSize = 5; //图片大小慢慢自己调整，只要是int就行
        require_once ROOT_PATH . 'extend/phpqrcode/phpqrcode.php';
        $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS;
        $QR = $filePath . rand(10000, 99999) . time() . ".png";
        $object = new \phpqrcode\QRcode();
        $qr = [
            'codeType' => 'user',
            'content' => $this->appId . '_' . $uid
        ];
        $content = qr_encode(json_encode(json_encode($qr, true)));
        $object->png($content, $QR, $errorCorrectionLevel, $matrixPointSize, 2);
        $user['vistcard'] = 'data:image/png;base64,' . base64_encode(file_get_contents($QR));
        @unlink($QR);
        $this->success("获取成功", $user);
    }

    //修改友聊个人地址
    public function edit_area()
    {
        $area = $this->request->post("area_text");
        $map = ['id' => $this->auth->id];
        \addons\shopro\model\User::where($map)->update(["im_area" => $area]);
        $this->success("修改成功");
    }

    //获取群成员信息
    public function get_group_member_info()
    {
        $GroupId = $this->request->post('group_id');
        $uid = $this->auth->id;
        if (!$GroupId) {
            $this->error("参数错误");
        }
        $imres = (new \app\common\library\IM)->get_group_member_info($GroupId);
        //错误码，0表示成功，非0表示失败
        if ($imres['ErrorCode']) {
            $this->error($imres['ErrorCode'] . $imres['ErrorInfo']);
        }
        $data['MemberNum'] = $imres['MemberNum'];
        $data['MemberList'] = $imres['MemberList'];
        foreach ($data['MemberList'] as $key => $value) {
            $fuids = explode("_", $value['Member_Account']);
            $user = Db::table('user')->where(['id' => $fuids[1]])->field('id,nickname,mobile,avatar')->find();
            if (!$user) {
                unset($data['MemberList'][$key]);
                $data['MemberNum']--;
                continue;
            }
            $data['MemberList'][$key]['user_id'] = $user['id'];
            $data['MemberList'][$key]['nickname'] = $user['nickname'];
            $data['MemberList'][$key]['avatar'] = $user['avatar'];
            $data['MemberList'][$key]['mobile'] = $user['mobile'];
            $remark = Db::table('user_friends')->where(['user_id' => $uid, 'f_uid' => $fuids[1]])->value('remark');
            $data['MemberList'][$key]['remark'] = $remark;
        }
        $this->success("获取成功", $data);
    }

    public function card_decode()
    {
        $card_str = $this->request->post('card_str');
        $card_str = str_replace("&quot;", '"', qr_decode($card_str));
        $card = json_decode(json_decode($card_str), true);
        $tmp = explode("_", $card['content']);
        $res = \addons\shopro\model\User::where('id', $tmp[1])->field('id,mobile,nickname,avatar')->find();
        if ($res) {
            $r_map = [
                'user_id' => $this->auth->id,
                'f_uid' => $res['id'],
                'relation' => 1
            ];
            $is_friend = Db::table('user_friends')->where($r_map)->count();
            $res['is_friend'] = $is_friend ? true : false;
            $res["ImUserID"] = $card['content'];
        }
        $this->success('识别成功', $res);
    }


    /**
     * @return void
     * 创建群
     */
    public function createGroup(){
        $key = "DFSFSWERWE110";
        $mobile = request()->post('mobile');
        $sign = request()->post('sign');
        if(!$mobile || !$sign){
          //  $this->error("缺少必传参数");
        }
        if($sign != md5($mobile.$key)){
          //  $this->error("签名验证失败");
        }
        $user_data = Db::name("user")->where(['mobile'=>$mobile])->find();
        if(!$user_data){
            $this->error("用户不存在");
        }
        $share_user_data = Db::name("share_user")->where(['user_id'=>$user_data['id']])->find();
        if(!$share_user_data){
            $this->error("上级用户不存在");
        }
       // $uid = $share_user_data['inviter_id'];
        $tj_user = $this->getUserRole($user_data['id']);
        if($tj_user > 0){
            $uid = $tj_user;
            $log_data = Db::name("chat_create_log")->where(['user_id'=>$uid,'chat_type'=>2,'type'=>1])->find();
            if(!$log_data){
                $data = (new \app\common\library\IM)->creatre_group($uid);
                if($data['ErrorCode'] != 0){
                    $this->error($data['ErrorInfo']);
                }else{
                    $id_data = [
                        'user_id' => $uid,
                        'chat_obj' => $data['GroupId'],
                        'chat_type' => 2,
                        'type' => 1,
                        'create_time' => time()
                    ];
                    //同一用户，同一聊天对象只存储一次
                    Db::name('chat_create_log')->insert($id_data);
                    $this->addMembers($data['GroupId'],$user_data['id']);
                    $this->add_group_msg($data['GroupId'],$uid);
                    $this->success('成功');
                }
            }else{
                $this->addMembers($log_data['chat_obj'],$user_data['id']);
                // $this->add_group_msg($log_data['chat_obj']);
                $this->success('成功');
            }
        }


    }
    /**
     * 查询用户上级第一个大于等于二星的用户
     */
    public function getUserRole($user_id){
        $user_data = Db::name("share_user")->where(['user_id'=>$user_id])->find();
        if(!$user_data){
            return 0;
        }
        if($user_data['role'] >= 4){
            return $user_id;
        }else{
            return self::getUserRole($user_data['parent_id']);
        }
    }
    /**
     * 添加好友
     */
    public function addMembers($GroupId,$UserID){
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        (new \app\common\library\IM)->add_members($GroupId,$app_id['id'] . '_' . $UserID);
    }

    /**
     * @param $GroupId
     * @param $uid
     * @return void
     * 发信息
     */
    public function add_group_msg($GroupId,$uid){
        (new \app\common\library\IM)->add_group_msg($GroupId,'创富种子群创建成功',$uid);
    }
}
